package com.me.seckill.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 自定义 rabbitMQTemplate：
 * 1，消息确认回调
 * 2，队列投递失败回调
 *
 * @author ME
 * @date 2021/7/14
 */
@Component
public class RabbitTemplateConfig {

    private static final Logger log = LoggerFactory.getLogger(RabbitTemplateConfig.class);

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init() {
        // 消息只要被 rabbitmq broker 接收到就会触发 confirmCallback 回调
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                if (ack) {
                    log.info("发送者收到确认。\n    ===> correlationData={} ,ack={}, cause={}", correlationData.getId(), ack, cause);
                } else {
                    log.error("消息发送异常!");
                }
            }
        });

        // Exchange 收到消息后却无法将该消息路由到任何一个队列，那么该消息将返回给生产者，触发 returnCallback 回调
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                log.info("队列投递失败！\n    ===> replyCode={}, replyText={}, exchange={}, routingKey={}", replyCode, replyText, exchange, routingKey);
            }
        });
    }

}
